package com.snbc.string;

public class Demo2 {
    public static void main(String[] args) {
        /*随机生成1000个2位字符串，查找生否有相同的字符串 并找出他们的个数*/
        String[] str = new String[1000];
        for (int i = 0; i < str.length; i++) {
            str[i] = randomStr(2);
            System.out.print(str[i] + " ");
            // 美观输出字符串数组
            if (i != 0 && (i + 1) % 20 == 0)
                System.out.println();
        }
        int sum = 0; // 重复的字符串的种数
        String[] str2 = new String[100000]; // 用于存放重复的字符串
        int n = 0;
        for (int i = 0; i < str.length - 1; i++) {
            int j;
            // 判断当前字符串是否已经存储于str2数组，若存在则已经是重复字符串，无须比较了
            for (j = 0; j < str2.length; j++) {
                if (str[i] == str2[j])
                    break;
            }
            if (j != str2.length) {
                continue;
            } else {
                for (int k = i + 1; k < str.length; k++) {
                    if (str[i].equals(str[k])) {
                        sum++;
                        str2[n++] = str[i];
                        break;
                    }
                }
            }
        }
        System.out.printf("总共有 %d种重复的字符串%n", sum);
        System.out.println("分别是：");
        for (String s : str2) {
            if (s == null) {
                break;
            }
            System.out.print(s + " ");
        }
    }

    private static String randomStr(int length) {
        char[] str = new char[length];
        int a;
        for (int i = 0; i < str.length; i++) {
            while (true) {
                a = (int) (Math.random() * 100 + 23); // 23~122的随机数（取不到123）
                // if (48 <= a && a <= 57 || 65 <= a && a <= 90 || 97 <= a && a <= 122)
                if ('0' <= a && a <= '9' || 'A' <= a && a <= 'Z' || 'a' <= a && a <= 'z')
                    break;
            }
            str[i] = (char) a;
        }
        String s = new String(str);
        return s;
    }
}
